// setGroupManager
package Network

import (
	"SQL/db"
	"logs"
)

//setGroupManager groupID="123456" managerIDs=["345","123"]

func setGroupManager(clientID string, args interface{}) (response *ServerResponse) {
	code := Success
	msg := ""
	var res interface{}
	defer func() {
		if code != Success {
			logs.Print("code: ", code, " msg: ", msg)
		}
		response = &ServerResponse{
			Method:  "/setGroupManager",
			Code:    code,
			Message: msg,
			Result:  res,
		}
	}()
	Args, ok := args.(map[string]interface{})
	var argsmap zd_argmap
	if ok {
		argsmap = Args
		groupID, ok := argsmap["groupID"].(string)
		if !ok {
			code = errAssertType
			msg = errAssertMsg
			return
		}
		msg, code = checkArgs("groupID", groupID)
		if code != Success {
			return
		}
		msg, code = checkisExistGroup(groupID)
		if code != Success {
			return
		}
		msg, code = checkOwnerofGroup(clientID, groupID)
		if code != Success {
			return
		}
		managers, ok := argsmap["managers"]
		if !ok {
			code = errAssertType
			msg = errAssertMsg
			return
		}
		switch arrayofmanagers := managers.(type) {
		case []interface{}:
			if len(arrayofmanagers) == 0 {
				code = errEmptyParameter
				msg = clientID + " You have not selected any user to become an manager"
				return
			}
			if len(arrayofmanagers) > 9 {
				code = errTooManyManager
				msg = "管理员人数超过上限，上限为9人，请检查"
				return
			}
			msg, code = setGroupManagerToDB(groupID, arrayofmanagers)
			if code != Success {
				return
			}
		default:
			code = errInvalidManager
			msg = "managers 参数的格式为 []string,请检查"
		}
	}
	return
}

func setGroupManagerToDB(groupID string, managers []interface{}) (msg string, code int) {
	DB := db.Open()
	defer db.Close(DB)
	tx, err := DB.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()
	var sql string
	rows, err := db.RowQuery("select owner from groups where id = $1", groupID)
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	defer rows.Close()
	var owner string
	for rows.Next() {
		err = rows.Scan(&owner)
		if err != nil {
			code = errRowsScan
			msg = err.Error()
			return
		}
	}
	sql = "update members set ismanager = false where ismanager = true and groupid =$1 and userid !=$2 "
	err = db.TxExec(tx, sql, groupID, owner)
	if err != nil {
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	var managersmap map[string]string
	managersmap = make(map[string]string)
	for _, v := range managers {
		_, ok := managersmap[v.(string)]
		if ok {
			code = errExistSameParam
			msg = "管理员数组中存在重复的userID"
			return
		}
		managersmap[v.(string)] = v.(string)
	}
	for _, manager := range managersmap {
		if manager == "" {
			code = errEmptyParameter
			msg = "managers 中存在空参数"
			return
		}
		msg, code = checkArgs("userID", manager)
		if code != Success {
			return
		}
		msg, code = checkUserInGroup(manager, groupID)
		if code != Success {
			return
		}
		sql = "update members set ismanager = true where groupid =$1 and userid =$2"
		err = db.TxExec(tx, sql, groupID, manager)
		if err != nil {
			code = errDBQueryFailed
			msg = err.Error()
			return
		}
	}
	err = tx.Commit()
	if err != nil {
		code = errEndTx
		msg = err.Error()
		return
	}
	return "设置管理员成功", Success
}
